<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.topic"
        clearable
        style="width: 250px"
        class="filter-item"
        placeholder="题目名称"
      />
      <el-select v-model="listQuery.isActive" class="filter-item" clearable placeholder="问卷状态">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button
        v-permission="['GET /admin/doctor/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        row-key="id"
        @click="handleFilter"
      >查找
      </el-button>
      <el-button
        v-permission="['POST /admin/doctor/create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中..."
      border
      fit
      highlight-current-row
      @expand-change="handleExpandChange"
      row-key="id"
      :expand-row-keys="expandKeys"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table
            :data="scope.row.orgDepts"
            v-loading="!scope.row.expand"
            border
            style="width: 94%; margin-left: 3%"
          >
            <el-table-column align="center" label="ID" prop="id" width="80"/>
            <el-table-column align="left" label="选项名称" prop="optionName"/>
            <el-table-column align="left" label="选项值" prop="optionValue"/>

            <el-table-column
              align="center"
              label="操作"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="s">

                <el-button
                  v-permission="['POST /admin/orgDoctor/update']"
                  type="primary"
                  size="mini"
                  @click="handleUpdateOrg(s.row)"
                >编辑
                </el-button>
                <el-button
                  v-permission="['POST /admin/orgDoctor/delete']"
                  type="danger"
                  size="mini"
                  @click="handleDeleteOrg(s.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="ID"
        prop="id"
        sortable
        width="120"
      />
      <el-table-column align="center" label="问卷名称" prop="topic"/>

      <el-table-column align="center" label="参考值" prop="normalVal"/>

      <el-table-column align="center" label="提示" prop="mark"/>


      <el-table-column align="center" label="状态" prop="isActive" width="140">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isActive == 0" type="danger">无效</el-tag>
          <el-tag v-else>有效</el-tag>
        </template>
      </el-table-column>


      <el-table-column align="center" label="适用性别" prop="isActive" width="140">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex == 1" type="success">男</el-tag>
          <el-tag v-else-if="scope.row.sex == 2" type="danger">女</el-tag>
          <el-tag v-else>不限</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="创建日期"
        prop="createTime"
        width="200"
      />

      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
        fixed="right"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/orgDoctor/create']"
            type="success"
            size="mini"
            @click="handleCreateOrg(scope.row)"
          >添加选项
          </el-button>
          <el-button
            v-permission="['POST /admin/doctor/update']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['POST /admin/doctor/delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus] + '题目'"
      :visible.sync="dialogFormDoctorVisible"
    >
      <el-form
        ref="dataFormDoctor"
        :rules="rulesTopic"
        :model="dataFormDoctor"
        status-icon
        label-position="right"
        label-width="100px"
        style="width: 90%; margin: 0 50px"
      >
        <el-row>

          <el-form-item label="题目" prop="topic">
            <el-input
              v-model="dataFormDoctor.topic"
              placeholder="题目"
              style="width: 100%"
            />
          </el-form-item>

        </el-row>

        <el-row>
          <el-form-item label="参考值" prop="normalVal">
            <el-input
              v-model="dataFormDoctor.normalVal"
              placeholder="参考值"
              style="width: 100%"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="提示" prop="mark">
            <el-input
              v-model="dataFormDoctor.mark"
              placeholder="如：一个中等大小苹果≈200克"
              style="width: 100%"
            />
          </el-form-item>
        </el-row>


        <el-form-item label="有效状态" prop="isActive">
          <el-switch v-model="dataFormDoctor.isActive" :active-value="true"
                     :inactive-value="false"
                     active-text="有效"
                     inactive-text="无效"/>
        </el-form-item>

        <el-form-item label="适用性别" prop="sex">
          <el-radio-group v-model="dataFormDoctor.sex">
            <el-radio :label="0">不限</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDoctorVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          :loading="saveLoading"
          @click="createData"
        >确定
        </el-button
        >
        <el-button v-else type="primary" :loading="saveLoading" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="textMap[dialogStatus]+'选项'"
      :visible.sync="dialogFormOrgDoctorVisible"
    >
      <el-form
        ref="dataFormOrgDoctor"
        :rules="rulesOptions"
        :model="dataFormOrgDoctor"
        status-icon
        label-position="right"
        label-width="100px"
        style="width: 90%; margin: 0 50px"
      >


        <el-row>
          <el-col :span="24">
            <el-form-item label="选项名称" prop="optionName">
              <el-input
                v-model="dataFormOrgDoctor.optionName"
                autofocus
                placeholder="请输入名称"
              />
            </el-form-item>

            <el-form-item label="选项值" prop="optionValue">
              <el-input
                v-model="dataFormOrgDoctor.optionValue"
                autofocus
                placeholder="请输入值"
              />
            </el-form-item>
          </el-col>

        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormOrgDoctorVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'add'"
          type="primary"
          @click="createDataOrg"
          :loading="orgFormSaveLoading"
        >确定
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="updateDataOrg"
          :loading="orgFormSaveLoading"
        >确定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .cert-uploader .el-upload {
    width: 96px;
    height: 96px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .cert-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .cert-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 64px;
    height: 64px;
    line-height: 64px;
    text-align: center;
  }

  .cert {
    width: 96px;
    height: 96px;
    display: block;
    object-position: center;
    object-fit: contain;
  }

  .desc_txt {
    color: #999;
  }
</style>

<script>
  import {
    topicList,
    topicCreate,
    topicUpdate,
    topicDelete,
    answerCreate,
    answerUpdate,
    answerDelete,
    answerList
    //   readDoctor,
    //   orgDoctorTree
  } from '@/api/topic_answer'

  import Pagination from '@/components/Pagination'

  import { uploadHeaders } from '../../utils/auth'

    const options = [{
    value: 0,
    label: '无效'
  }, {
    value: 1,
    label: '有效'
  }]

  export default {
    name: 'Doctor',
    components: { Pagination },
    data() {
      return {
        options,
        expandKeys: [],
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          isActive: undefined,
          topic: undefined,
          page: 1,
          limit: 20,
          size: 20,
          sort: 'create_time',
          order: 'desc'
        },

        dataFormDoctor: {
          id: undefined,
          topic: '',
          normalVal: '',
          sex: 0,
          isActive: 1,
          mark: ''
        },
        dialogFormDoctorVisible: false,

        dataFormOrgDoctor: {
          id: undefined,
          optionName: undefined,
          optionValue: undefined,
          topicId: undefined

        },
        dialogFormOrgDoctorVisible: false,

        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建',
          add: '增加'
        },

        file: undefined,

        rulesTopic: {
          topic: [{ required: true, message: '题目不能为空', trigger: 'blur' }]
        },

        rulesOptions: {
          optionName: [{ required: true, message: '不能为空', trigger: 'blur' }],
          optionValue: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ]
        },
        orgFormSaveLoading: false,
        saveLoading: false
      }
    },
    computed: {
      headers() {
        uploadHeaders(),
      }
    },
    created() {
      // this.getOrgList();
      // this.getOrgDoctorTree()
      this.getList()
    },
    methods: {

      getList() {
        this.listLoading = true
        topicList(this.listQuery)
          .then((response) => {
            let list = response.data.data.list
            for (let i in list) {
              list[i].expand = false
              list[i].orgDepts = []
            }

            this.list = list
            this.total = response.data.data.total
            this.listLoading = false

            this.expandKeys = []
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },

      handleExpandChange(row, expandRows) {
        if (row.expand) {
          // this.expandRowIds.shift("")
          return
        }
        this.expandKeys = [row.id]
        row.expand = true

        answerList({ topicId: row.id })
          .then((response) => {
            row.orgDepts = response.data.data

          })
          .catch()
      },

      resetFormDoctor() {
        this.dataFormDoctor = {
          id: undefined,
          topic: '',
          normalVal: '',
          sex: 0,
          isActive: 1,
          mark: ''

        }
      },
      resetFormOrgDoctor() {
        this.dataFormOrgDoctor = {
          id: undefined,
          optionName: undefined,
          optionValue: undefined,
          topicId: undefined

        }
      },

      handleCreate() {
        this.resetFormDoctor()
        this.dialogStatus = 'create'
        this.dialogFormDoctorVisible = true
        this.$nextTick(() => {
          this.$refs['dataFormDoctor'].clearValidate()
        })
      },
      createData() {
        let that = this
        this.$refs['dataFormDoctor'].validate((valid) => {
          if (valid) {
            that.saveLoading = true
            topicCreate(this.dataFormDoctor)
              .then((response) => {
                that.saveLoading = false
                this.getList()
                this.dialogFormDoctorVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch((response) => {
                that.saveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.resetFormDoctor()
        this.dataFormDoctor = Object.assign(this.dataFormDoctor, row)
        this.dialogStatus = 'update'
        this.dialogFormDoctorVisible = true

        this.$nextTick(() => {
          this.$refs['dataFormDoctor'].clearValidate()
        })
      },

      updateData() {
        let that = this
        this.$refs['dataFormDoctor'].validate((valid) => {
          if (valid) {
            that.saveLoading = true
            topicUpdate(this.dataFormDoctor)
              .then(() => {
                that.saveLoading = false
                this.getList()
                this.dialogFormDoctorVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch((response) => {
                that.saveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('删除题目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            topicDelete(row.id)
              .then((response) => {
                this.$notify.success({
                  title: '成功',
                  message: '删除成功'
                })
                this.getList()
              })
              .catch((response) => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          })
          .catch()
      },

      handleCreateOrg(row) {
        this.resetFormOrgDoctor()
        this.dialogStatus = 'add'
        this.dialogFormOrgDoctorVisible = true
        this.$nextTick(() => {
          this.$refs['dataFormOrgDoctor'].clearValidate()
        })

        this.dataFormOrgDoctor.topicId = row.id
      },
      createDataOrg() {
        console.log('createDataOrg')
        let that = this
        this.$refs['dataFormOrgDoctor'].validate((valid) => {
          if (valid) {
            that.orgFormSaveLoading = true
            answerCreate(this.dataFormOrgDoctor)
              .then((response) => {
                that.orgFormSaveLoading = false
                this.getList()
                this.dialogFormOrgDoctorVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch((response) => {
                that.orgFormSaveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdateOrg(row) {
        this.dataFormOrgDoctor = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormOrgDoctorVisible = true

        this.$nextTick(() => {
          this.$refs['dataFormOrgDoctor'].clearValidate()
        })
      },
      updateDataOrg() {
        console.log('updateDataOrg')
        let that = this
        this.$refs['dataFormOrgDoctor'].validate((valid) => {
          if (valid) {
            that.orgFormSaveLoading = true
            answerUpdate(this.dataFormOrgDoctor)
              .then(() => {
                that.orgFormSaveLoading = false
                this.getList()
                this.dialogFormOrgDoctorVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch((response) => {
                that.orgFormSaveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleDeleteOrg(row) {
        this.$confirm('删除部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            answerDelete(row.id)
              .then((response) => {
                this.$notify.success({
                  title: '成功',
                  message: '删除成功'
                })
                this.getList()
              })
              .catch((response) => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          })
          .catch()
      }
    }
  }
</script>
